// JavaScript Document
/*
拖拽插件 
powered b千百度 
2015.4.22.
 */
/*
调用方式：drag('');
只需传入元素id或者clss类名即可;
id调用方式：drag('#box');
class调用方式：drag('.box');
 */
function drag(box){
	$(box).mousedown(function(event) {
		// 获取鼠标按下时的xy坐标
		oldMouseX=event.pageX;
		oldMouseY=event.pageY;
		//记录元素区块的默认初始值
		oldBlockX=$(this).offset().left;
		oldBlockY=$(this).offset().top;
			$(document).mousemove(function(e) {
				// 获取移动鼠标位置
				var newMouseX = e.pageX;
				var newMouseY = e.pageY;
				// 新的鼠标位置- 就得鼠标位置 的出移动距离
				diffX = newMouseX -oldMouseX;
				diffY = newMouseY -oldMouseY;
				// 计算新的区块位置
				newBlockX = oldBlockX + diffX;
				newBlockY = oldBlockY + diffY;
				// 获取页面最大可视区域宽高
				windowW = document.documentElement.clientWidth;
				windowH = document.documentElement.clientHeight;
				// 获取区块宽高
				blockW = $(box).outerWidth() ;
				blockH = $(box).outerHeight() ;
				// 获取最大也移动宽高
				bigW = windowW - blockW;
				bigH = windowH - blockH;
				// 位置判断 是否超出边界
				if(newBlockX<=0){
					newBlockX=0;
				}
				if(newBlockX>=bigW){
					newBlockX = bigW;
				}
				if(newBlockY<=0){
					newBlockY=0;
				}
				if(newBlockY>=bigH){
					newBlockY = bigH;
				}
				// 把差值赋默认区块位置
				$(box).css({'left':newBlockX +'px','top':newBlockY +'px'});
			})

	})
	$(document).mouseup(function() {
		$(document).off('mousemove');
	});
}